package cn.texous.demo.dmqs.producer;

import cn.texous.demo.dmqs.config.NsqConfig;
import com.github.brainlag.nsq.NSQProducer;
import com.github.brainlag.nsq.exceptions.NSQException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeoutException;

/**
 * insert description here
 *
 * @author Showa.L
 * @since 2019/8/6 14:53
 */
@Slf4j
@Component
public class NsqProducer {

    @Autowired
    private NsqConfig nsqConfig;
    private static NSQProducer producer;

    @PostConstruct
    private void init() {
        producer = new NSQProducer();
        producer.addAddress(nsqConfig.getHost(), nsqConfig.getProducerPort()).start();
    }

    /**
     * 发送 nsq 消息
     *
     * @param message 消息
     */
    public void send(String message) {
        try {
            String topic = nsqConfig.getTpinfos().get("test").get(0);
            log.info("send nsq message: topic={}, message={}", topic, message);
            producer.produce(topic, message.getBytes());
        } catch (NSQException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

}
